﻿using System;
using System.Collections.Generic;
using System.Configuration;
using Microsoft.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Runtime.ExceptionServices;
//using Microsoft.Extensions.Configuration;


namespace Zhaoxi.Industrial.DAL
{
    /// <summary>
    /// 三大架构DAL 类
    /// </summary>
    internal class DataAccess
    {
        //readonly IConfiguration configuration;
        //"Server=localhost;Database=zx_scada_data;User Id=Sa;Password=Sa123;TrustServerCertificate=True;MultipleActiveResultSets=true";
        string dbconfig = JsonTool.GetKeyCode("DefaultConnection");

        SqlConnection sCon;//开闭连接
        SqlCommand sCod;   //执行数据库指令 ExecuteNonQuery、ExecuteReader、ExecuteScalar等方法来执行命令。
        SqlDataAdapter sDapter; //SqlDataAdapter通过SelectCommand、InsertCommand、UpdateCommand和DeleteCommand属性提供了对数据库的查询、插入、更新和删除操作。
        SqlTransaction sTrans; //表示一个数据库事务。

        public void Dispose() {
            if (sCon != null)
            {
                sCon.Dispose();
                sCon = null;
            }
            if (sCod != null)
            {
                sCod.Dispose();
                sCod = null;
            }
            if (sDapter != null)
            {
                sDapter.Dispose();
                sDapter = null;
            }
            if (sTrans != null)
            {
                sTrans.Dispose();
                sTrans = null;
            }
        }

        private DataTable GetDatas(string sql) {

            DataTable tb = new DataTable();
            try
            {
                
                //创建连接
                sCon = new SqlConnection(dbconfig);
                //打开链接
                sCon.Open();

                sDapter = new SqlDataAdapter(sql, sCon);
                sDapter.Fill(tb);

            }
            catch (Exception ex)
            {
                ExceptionDispatchInfo.Capture(ex).Throw();
                //其中包括对异常堆栈信息的处理。如果你在代码中再次捕获并重新抛出一个异常，并且修改了异常信息或者添加了新的信息，那么默认情况下，.NET 7会警告你这样做可能会更改原始异常的堆栈信息。 throw ex
                //确保了当你重新抛出异常时，堆栈信息不会被修改，从而保持了异常的原始上下文。
            }
            finally
            {
                this.Dispose();
            }
            return tb;

        }

        public DataTable GetDevices()
        {
            string sql = "select * from devices";
            return (this.GetDatas(sql));
        }

        public DataTable GetMonitor_values()
        {
            string sql = "select * from monitor_values order by d_id,value_name";
            return (this.GetDatas(sql));
        }

        public DataTable GetStorage_area()
        {
            string sql = "select * from storage_area";
            return (this.GetDatas(sql));
        }


    }
}
